#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author : bird.zhang@ximalaya.com

import sys

import pandas as pd

from .argparser import *
from .constant import *
from .cryptor import *
from .util.file_util import *


def check_auth_decorator(func):
    """
    对check_auth()进行decorator化
    """

    def wrapper(args):
        message = open(constant.DECODE_STR_FILE_PATH).readline().rstrip('\n')
        ciphertext = open(constant.ENCODE_STR_FILE_PATH).readline().rstrip('\n')
        if check_auth(message, ciphertext, args.password):
            func(args)
        else:
            raise AuthFailedException

    return wrapper


def read_dataframe_from_file(file_path, key):
    df = pd.read_csv(file_path, encoding=CHARSET_UTF8)
    # 解密
    #
    df[USERNAME] = df[USERNAME].map(lambda x: Cryptor(key).decrypt(x))
    df[PASSWORD] = df[PASSWORD].map(lambda x: Cryptor(key).decrypt(x))
    return df


def store_dataframe_to_file(file_path, df, key):
    # 加密
    df[USERNAME] = df[USERNAME].map(lambda x: Cryptor(key).encrypt(x))
    df[PASSWORD] = df[PASSWORD].map(lambda x: Cryptor(key).encrypt(x))
    df.to_csv(file_path, index=False, encoding=CHARSET_UTF8)


def init(args):
    # 1. 判断~/.pyaccount/store.data文件是否存在
    if file_existed(STORE_DATA_FILE_PATH):
        print('File has existed, no need init!')
        return
    # 2. 新建~/.pyaccount/store.data文件
    if not os.path.isdir(PYACCOUNT_HOME):
        os.makedirs(PYACCOUNT_HOME)
    df = pd.DataFrame(columns=[ADDRESS, USERNAME, PASSWORD])
    store_dataframe_to_file(STORE_DATA_FILE_PATH, df, args.password)
    print('Init Success!')


@check_auth_decorator
def add(args):
    # 1. 判断~/.pyaccount/store.data文件是否存在
    assert_file_exist(STORE_DATA_FILE_PATH)

    df = read_dataframe_from_file(STORE_DATA_FILE_PATH, args.password)
    _df = pd.DataFrame({ADDRESS: [args.args[0]], USERNAME: [args.args[1]], PASSWORD: [args.args[2]]})
    df = df.append(_df, ignore_index=True)
    store_dataframe_to_file(STORE_DATA_FILE_PATH, df, args.password)
    print('Add Success!')


@check_auth_decorator
def delete(args):
    assert_file_exist(STORE_DATA_FILE_PATH)

    df = read_dataframe_from_file(STORE_DATA_FILE_PATH, args.password)
    df = df[df[ADDRESS] != args.args[0]]
    store_dataframe_to_file(STORE_DATA_FILE_PATH, df, args.password)
    print('Delete Success!')


@check_auth_decorator
def modify(args):
    assert_file_exist(STORE_DATA_FILE_PATH)

    print('Unsupport Operation!!!')


@check_auth_decorator
def find(args):
    # 1. 判断~/.pyaccount/store.data文件是否存在
    assert_file_exist(STORE_DATA_FILE_PATH)

    df = read_dataframe_from_file(STORE_DATA_FILE_PATH, args.password)
    if args.args and ([] != args.args):
        df[ADDRESS] = df[ADDRESS].apply(str)
        df = df[df[ADDRESS].str.contains(args.args[0])]
    # 列表按照一定顺序排序显示
    df = df[[ADDRESS, USERNAME, PASSWORD]]
    print(df.values)


def run():
    if len(sys.argv) == 1:
        sys.argv.append('--help')

    parser = gen_parse()
    args = parser.parse_args()

    # for debug
    if args.debug:
        print('password = ' + args.password)
        print('command = ' + args.command)
        print('args = ' + str(args.args))

    # 其他执行逻辑
    if args.command == 'init':
        init(args)
    elif args.command == 'add':
        add(args)
    elif args.command == 'delete':
        delete(args)
    elif args.command == 'modify':
        modify(args)
    elif args.command == 'find':
        find(args)
    else:
        print('Attention!!! Unknow command : %s' % args.command)
        parser.print_help()
